<template>
    <!-- 角色信息 -->
    <div class="box">
        <div>
            <a-row>
                <a-col :span="12" class="inp">
                    <a-form-item label="名字" class="inp_item">
                        <a-input v-model:value="search_info" placeholder="请输入" />
                    </a-form-item>
                </a-col>
                <a-col :span="12" class="pluss">
                    <div class="pluss_item" @click="reset">
                        <span>重置</span>
                    </div>
                    <div class="pluss_item" @click="search">
                        <SearchOutlined />
                        <span>查询</span>
                    </div>
                    <div class="pluss_item" @click="poput('')">
                        <PlusOutlined />
                        <span>新建</span>
                    </div>
                </a-col>
            </a-row>
        </div>
        <div>
            <a-table :data-source="data" :columns="columns" :pagination="false">
                <template #name="{ text, record }">
                    <div class="editable-cell">
                        <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
                            <a-input v-model:value="editableData[record.key].name" @pressEnter="save(record.key)" />
                            <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
                        </div>
                        <div v-else class="editable-cell-text-wrapper">
                            {{ text || ' ' }}
                            <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
                        </div>
                    </div>
                </template>
                <template #operation="{ record }" v-slot:bodyCell="{columns,record}">
                    <FormOutlined class="revise_info" @click="revise(record)" />
                    <a-popconfirm v-if="data.length" title="是否删除?" @confirm="onDelete(record.key)">
                        <DeleteOutlined class="del_info" />
                    </a-popconfirm>
                </template>
            </a-table>
            <div class="pagination">
                <a-pagination :pageSize="5" :total="total" @change="paginat" />
            </div>
        </div>
        <a-modal v-model:open="open" title="编辑" @ok="poput" :afterClose="close">
            <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-item label="用户名" v-bind="validateInfos.name">
                    <a-input v-model:value="modelRef.name" placeholder="请输入" />
                </a-form-item>
                <a-form-item label="简介" v-bind="validateInfos.brief">
                    <a-textarea v-model:value="modelRef.brief" placeholder="请输入" allow-clear />
                </a-form-item>

                <a-form-item label="权限" v-bind="validateInfos.type">
                    <a-checkbox-group v-model:value="modelRef.type">
                        <a-checkbox :value="item.id" name="type" v-for="item in permissions" :key="item.id">{{ item.name
                        }}</a-checkbox>
                    </a-checkbox-group>
                </a-form-item>

            </a-form>
        </a-modal>
    </div>
</template>
<script setup>

import { ref, reactive } from 'vue';
import { get, post, patch, del } from '../../../utils/request'
import { Form, message } from 'ant-design-vue';
import { SearchOutlined, PlusOutlined, CheckOutlined, EditOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { cloneDeep } from 'lodash-es';
const columns = [
    {
        title: '序号',
        dataIndex: 'name',
        key: 'name',
        ellipsis: true,
        align: 'center'
    },
    {
        title: '名字',
        dataIndex: 'user',
        key: 'user',
        ellipsis: true,
        align: 'center'
    },
    {
        title: '描述',
        dataIndex: 'description',
        key: 'address 2',
        ellipsis: true,
        align: 'center'
    },
    {
        title: '权限',
        dataIndex: 'permissions',
        key: 'permissions',
        ellipsis: true,
        align: 'center'
    },
    {
        title: '操作',
        dataIndex: 'operation',
        key: 'address 4',
        ellipsis: true,
        align: 'center',
        slots: {
            customRender: 'operation',
        },

    },
];
const data = ref([])
const modifyEdits_id = ref('') // 判断修改还还是添加  空 为添加
const open = ref(false);
const arr_data = ref([])
const total = ref()
const permissions = ref([])
const useForm = Form.useForm;

const managers = async (page = 1) => {
    const managers = await get('/admin/roles', { per: 5, page })
    const res = await get('/admin/permissions')
    permissions.value = res.data.list
    data.value = []
    arr_data.value = managers.data.list
    managers.data.list.forEach(async (item, index) => {
        let permissions = ''
        item.permissionOnRoles.forEach(item1 => {
            permissions += res.data.list.filter(elem => elem.id == item1.permissionId)[0].name + ','
        })
        data.value.push({
            key: item.id,
            name: index + 1 + '',
            user: item.name,
            permissions,
            description: item.desc,
        })
    });
    total.value = managers.data.total
    console.log(permissions.value);
}
managers()
const poput = async () => {
    open.value = !open.value
    if (!open.value) {  // 添加删除
        const { name, brief, type } = modelRef.value
        if (name.trim() == '' || name.trim() == '' || type.length == 0) {
            return message.info('输入不能为空')
        }
        const addmanager = {
            "name": name,
            "desc": brief,
            permissions: '',
        }
        type.forEach(item => {
            addmanager.permissions += addmanager.permissions == '' ? item : ',' + item
        })
        if (modifyEdits_id.value != '') {
            patch('/admin/roles/' + modifyEdits_id.value, addmanager).then(res => {
                modifyEdits_id.value = ''
                message.success('修改成功')
                managers()
            }).catch(err => {
                message.error('修改失败,服务器错误')
            })
        } else {
            post('/admin/roles', addmanager).then(res => {
                data.value = []
                message.success('添加成功')
                managers()
                modelRef.value = {
                    name: '',
                    brief: ''
                }
            }).catch(err => {
                message.error('添加失败,服务器错误')
            })
        }
    }
}
// 关闭对话框回调
const close = () => {
    modelRef.value = {
        name: '',
        brief: '',
        type: []
    }
    modifyEdits_id.value = ''
}

const editableData = reactive({});
const edit = key => {
    editableData[key] = cloneDeep(data.value.filter(item => key === item.key)[0]);
};

// 删除
const save = key => {
    Object.assign(data.value.filter(item => key === item.key)[0], editableData[key]);
    delete editableData[key];
};
const onDelete = key => {
    del('/admin/roles/' + key).then(res => {
        message.success('删除成功')
    }).catch(err => {
        message.error('删除失败,服务器错误')
    })
    data.value = data.value.filter(item => item.key !== key);
};

// 修改
const revise = record => {
    open.value = !open.value
    const arr = record.permissions.split(',')
    arr.pop()
    const arr_type = permissions.value.filter(item => {
        if (arr.filter(item1 => item1 == item.name).length > 0) {
            return item
        }
    })
    modelRef.value = {
        name: record.user,
        brief: record.description,
        type: [...arr_type.map(item => item.id)]
    };

    modifyEdits_id.value = record.key
}
// 表单
const modelRef = ref({
    name: '',
    brief: '',
    type: []
});

const { validateInfos } = useForm(
    modelRef,
    reactive({
        name: [
            {
                required: true,
                message: '请输入',
            },
        ],
        brief: [
            {
                required: true,
                message: '请输入',
            },
        ],
        type: [
            {
                required: true,
                message: '请选择',
            },
        ],
    }),
);

const labelCol = { span: 4 }
const wrapperCol = { span: 14 }


// 分页
const paginat = (page) => {
    managers(page)
}
// 搜索
const search_info = ref('') // 用户
const search = () => {
    if (search_info.value.trim() == '') {
        return message.info('输入不能为空')
    }
    const data_arr = arr_data.value.filter(item => {
        if (item.name == search_info.value) {
            return item
        }
    })
    data.value = []
    data_arr.forEach((item, index) => {
        data.value.push({
            key: item.id,
            permissions: permissions.value.filter(elem => elem.id == item.permissionOnRoles[0].permissionId)[0].name,
            name: index + 1 + '',
            user: item.name,
            description: item.desc,
        })
    });

}
// 重置
const reset = () => {
    location.reload()
}
</script>
<style scoped>
.box {
    height: 100%;
    overflow-y: auto;
}

.inp {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.inp_item {
    flex: 1;
    padding: 0 5px;
}

.operate_but {
    display: flex;
    justify-content: center;
    align-items: center;
}

.operate_but .but1 {
    width: 60px;
    height: 20px;
}

:where(.css-dev-only-do-not-override-185kyl0).ant-col-8 {
    padding: 12px;
}

.file_img {
    width: 100%
}

.pagination {
    width: 100%;
    text-align: end;
    padding-top: 10px;
    box-sizing: border-box;
}

.pluss {
    display: flex;
    justify-content: end;
    align-items: center;
}

.pluss_item {
    width: 90px;
    height: 30px;
    background-color: #1890ff;
    text-align: center;
    line-height: 30px;
    margin-bottom: 20px;
    color: #fff;
    cursor: pointer;
}

.pluss .pluss_item:nth-child(1) {
    background-color: #fff;
    border: 1px solid #d9d9d9;
    color: #000;
}

.pluss .pluss_item:nth-child(2) {
    margin-left: 10px;
    margin-right: 10px;
}

.del_info,
.anticon {
    width: 30px;
    height: 30px;
    display: inline-block;
    text-align: center;
    line-height: 30px;
}

.del_info {
    margin: 0 10px;
    background-color: red !important;
    color: #fff !important;
}

.anticon[data-v-4e879eca]:nth-child(3) {
    background-color: #fff;
    color: #000;
    border: 1px solid #d9d9d9;
}

.revise_info {
    border: 1px solid #d9d9d9;
    background-color: #1890ff;
    color: #fff;
}
</style>